onion.register("onion.faces");

$(function(){
	onion.faces.formPanel.init();
});

onion.faces.showFullModalPanel = function(event,id,params){
	params = params || {};
	if(top != window){
		if(window.ActiveXObject){
			params.width = top.document.body.clientWidth - window.parent.frames['left'].document.body.clientWidth - 25;
			params.height = $(window.parent.frames['main']).height() - 5;
		}else{
			params.width = top.document.body.clientWidth - window.parent.frames['left'].document.body.clientWidth - 25;
			params.height = $(window.parent.frames['main']).height();
		}
	}else{
		params.width = document.body.clientWidth;
		params.height = document.body.clientHeight;
	}

	$(window).scrollTop(0);
	params.top = "0px";
	RichFaces.$(id).show(event,params);
};

//自动显示异常消息的开关
//这个属性每次显示完成后会恢复为true
onion.faces.showMessage = true;

//自动显示异常消息的开关
//可以在自定义的程序中覆盖这个属性
//从而总体控制不自动显示异常信息
onion.faces.preventMessage = false;

onion.faces.autoShowMessage = function(hasError){
	if(onion.faces.preventMessage)
		return;
	else if(!onion.faces.showMessage){
		onion.faces.showMessage = true;
		return;
	}

	if(hasError){
		onion.faces.message.show($('#formMessages'));
	}
	else{
		$(".messagesSpan").html($('#formMessages').html()).fadeIn();
		setTimeout(function(){
			$(".messagesSpan").fadeOut();
		},6000);
	}
	onion.faces.showMessage = true;
};

onion.faces.popupShowLoading = function(event){
	var content = event.rf.component.getContentElement();;
	$(".modalPanelContent", content).html("<div class=\"contentLoading\">正在加载...</div>");
};

/**
 * 通用模态框定义
 */
onion.faces.formPanel = {
	id : "formPanel",

	init: function() {
		this.comp = RichFaces.$("formPanel");
	},

	show: function(event,params) {
		this.overflowElement = "body";
		if($.browser.msie && $.browser.version <= 7)
			this.overflowElement = "html";
		this.bodyOverflow = $(this.overflowElement).css("overflow");
		$(this.overflowElement).css("overflow","hidden");
		
		onion.faces.showFullModalPanel(event,onion.faces.formPanel.id,params);
	},

	hide: function() {
		if(onion.faces.ajaxMenu)
			onion.faces.ajaxMenu.destroyMenus($("#formPanelInclude"));
		$(this.overflowElement).css("overflow",this.bodyOverflow);
		$("#formPanelInclude").html("<div class=\"contentLoading\">正在加载...</div>");
		this.comp.hide();
	},

	onrefresh : function(){}
};

/**
 * 直接打开表单时，应该用此方法替换onion.faces.formPanel.hide方法
 * 从而把hide方法转变为关闭页面，对于多标签页的应用，可能需要覆盖此
 * 方法，改成关闭标签页
 */
onion.faces.closePage = function(event){
	if(window.top == window)
		window.close();
	else
		window.location.href = onion.ctx + "/welcome.xhtml";
};

/**
 * 在直接访问的表单页面上，需要替换formPanel的hide方法，以兼容
 * 在formPanel中打开表单的情况
 * 
 * 另外，对于直接打开表单的情况，消息不应该用右上角的简单提示，
 * 应该使用对话框提醒，因为在消息显示完成后，可能需要关闭页面
 */
onion.faces.freeForm = function(){
	onion.faces.formPanel.hide = function(){
		onion.faces.closePage();
	};
	
	onion.faces.autoShowMessage = function(hasError){
		if(onion.faces.preventMessage)
			return;
		else if(!onion.faces.showMessage){
			onion.faces.showMessage = true;
			return;
		}

		onion.faces.message.show($('#formMessages'));	
		onion.faces.showMessage = true;
	};
};

Array.prototype.contains = function (element) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element)
			return true;
	}

	return false;
};

/**
 * 通用列表逻辑，实现行选择、校验
 */
onion.faces.list = {
	hasSelected : function(table){
		return this.getSelectedCount(table) != 0;
	},

	hasSingleSelected : function(table){
		return this.getSelectedCount(table) == 1;
	},

	checkSelected : function(table){
		if(onion.faces.list.hasSelected(table))
			return true;
		else{
			onion.faces.message.show('请至少选择一条记录');
			return false;
		}
	},

	checkSingleSelected : function(table){
		if(onion.faces.list.hasSingleSelected(table))
			return true;
		else{
			onion.faces.message.show('请选择一条记录');
			return false;
		}
	},

	addHover : function(row,add){
		if($(row).hasClass('selected'))
			return;

		$(row).addClass('row-hover');
	},

	removeHover : function(row){
		$(row).removeClass('row-hover');
	},

	dblClick : function(row,callback){

		if(typeof callback == "undefined" || callback == null)
			callback = ".tableButtons input[value='打开']";

		if(typeof callback == "string")
			$(callback).click();
		else if(typeof callback == "function")
			callback(row);
	},

	checkRow : function(checkbox,event){
		var box = $(checkbox);
		
		if(box.attr("disabled"))
			return;
		
		//如果是单选 在目前的css中，我们定义了单选的话不展现复选框列
		//所以其实这段代码不会执行，除非开发人员做了特殊的控制
		if(box.parents("table").hasClass("singleSelect")){
			var row = box.parent().parent();
			var checkedBoxes = $("td.checkboxcell input[name!='" + box.attr("name") + "'][disabled != true]:checked",row.parent());

			checkedBoxes.attr("checked",false);
			$(".selected",row.parent()).removeClass("selected").removeClass("row-hover");
		}

		if(checkbox.checked)
			box.parent().parent().addClass("selected");
		else
			box.parent().parent().removeClass("selected");

		if(window.ActiveXObject)
			event.cancelBubble = true;
		else if(event.stopPropagation)
			event.stopPropagation();
		
		this.submitSelection(box.parents("table").attr("id"));
	},

	checkAllRows : function(checkbox,event){
		var box = $(checkbox);
		var nextRows = box.parents("table:first").find("tbody").find("tr:has(td.checkboxcell :checkbox[disabled != true])");
		if(checkbox.checked){
			nextRows.addClass("selected");
			nextRows.find("td:first input[type='checkbox']").attr("checked",true);
		}
		else{
			nextRows.removeClass("selected");
			nextRows.find("td:first input[type='checkbox']").attr("checked",false);
		}
		
		this.submitSelection(box.parents("table").attr("id"));
	},

	selectRow : function(row,event){
		var checkbox = $(row.cells[0]).children()[0];
		checkbox = $(checkbox);
		
		if(checkbox.attr("disabled"))
			return;
		
		//取消全选框
		$(row).parent().prev("thead").find("tr th:first input[type='checkbox']").attr("checked",false);
		
		row = $(row);
		row.removeClass("row-hover");
		var selected = checkbox.attr("checked");
		
		var checkedBoxes = $("td.checkboxcell :checked[disabled != true]",row.parent());
		var selectedRows = $(".selected:has(:checkbox[disabled != true])",row.parent());
		
		if(selected) //被点击的行当前是选中状态
		{
			if(checkbox.parents("table").hasClass("singleSelect"))//如果是单选模式那么不做任何事
				return;

			//以下处理多选模式
			if(event.ctrlKey){//如果按住了ctrl键，那么取消当前行的选择
				checkbox.attr("checked",false);
				checkbox.parent().parent().removeClass("selected");

			}else{//如果没按ctrl键，那么取消其他行的选择
				if(checkedBoxes.length > 1){
					checkedBoxes.attr("checked",false);
					selectedRows.removeClass("selected");
					checkbox.attr("checked",true);
					checkbox.parent().parent().addClass("selected");
				}
				/*
				else{
					checkbox.attr("checked",false);
					checkbox.parent().parent().removeClass("selected");
				}
				*/
			}
		}
		else{//被点击的行当前没有被选中
			if(!checkbox.parents("table").hasClass("singleSelect")){//多选模式
				if(event.shiftKey){//如果按下了shift键，那么需要处理一次多选
					var rowIndex = row.attr("rowIndex");
					var startIndex = -1;
					var tempCell;
					if(rowIndex != 0){
						for(var i=rowIndex -1;i>=0;i--){
							tempCell = row.parent().parent()[0].rows[i].cells[0];
							if($("input[type='checkbox']",$(tempCell)).attr("checked"))
							{
								startIndex = i;
							}else if(startIndex != -1)
								break;
						}

						checkedBoxes.attr("checked",false);
						selectedRows.removeClass("selected").removeClass("row-hover");

						if(startIndex != -1){
							selectedRows.removeClass("selected").removeClass("row-hover");
							checkedBoxes.attr("checked",false);
							var rows = row.parent().children();
							for(var i=startIndex - 1;i<rowIndex;i++){
								if($("td:first :checkbox[disabled]",rows[i]).length > 0)
									continue;
								$(rows[i]).addClass("selected");
								$("td:first input[type='checkbox']",rows[i]).attr("checked",true);
							}
						}
					}
				}else if(!event.ctrlKey){//如果不是ctrl键，那么取消其他行的选中状态
					checkedBoxes.attr("checked",false);
					selectedRows.removeClass("selected").removeClass("row-hover");
				}
			}else{//如果是单选，那么取消其他行的选中状态
				checkedBoxes.attr("checked",false);
				selectedRows.removeClass("selected").removeClass("row-hover");
			}

			checkbox.parent().parent().addClass("selected");
			checkbox.attr("checked",true);

			delete row;
			delete checkbox;
			delete checkboxes;

		}
		
		this.submitSelection(row.parents("table").attr("id"));
	},
	
	submitSelection : function(tableId){
		//调用jsf:tableSelectionHolder中定义的function
		var submitSelectionFunction = window["submitSelection_" + tableId.replace(":","_")];
		if(typeof submitSelectionFunction != "undefined")
			submitSelectionFunction();
	},
	
	setClassToSelectedRow : function(id){
		var checkedBoxes = $(":checked",$(document.getElementById(id)));
		
		checkedBoxes.each(function(index,item){
			$(item).parent().parent().addClass("selected");
		});
	},
	
	processSelection : function(id,count,dataCount){
		this.setClassToSelectedRow(id);
		var table = $(document.getElementById(id));
		table.attr("selectedCount",count).attr("dataCount",dataCount);
		var selectedInThisPage = $(":checked",$("tbody",table)).length;
		table.attr("selectedCountInCurrentPage",selectedInThisPage);
	},
	
	getSelectedCount : function(id){
		var table = $(document.getElementById(id));
		var selectedInThisPage = $(":checked",$("tbody",table)).length;
		
		//原本全部选中的记录数（包括本页与其他页）
		var oriSelected = table.attr("selectedCount");
		if(oriSelected == null)oriSelected = 0;
		else oriSelected = oriSelected * 1;
		
		//本页加载时选中的记录数
		var oriSelectedInThisPage = table.attr("selectedCountInCurrentPage");
		if(oriSelectedInThisPage == null)oriSelectedInThisPage = 0;
		else oriSelectedInThisPage = oriSelectedInThisPage * 1;
		
		//当前选中记录数=原本总的选中数-原本当页选中数+现在本页选中数
		//其中（原本总的选中数-原本当页选中数）实际上就是其他页的选中数量
		return oriSelected - oriSelectedInThisPage + selectedInThisPage;
	},
	
	getDataCount : function(id){
		var table = $(document.getElementById(id));
		var count = table.attr("dataCount");
		if(count == null)
			throw "当前table[" + id + "]没有设置总记录数";
		else
			return count * 1;
	},
	
	toggleQueryFields : function(panelId){
		var obj = $(document.getElementById(panelId + "Container"));
		var tool = obj.find(".toggleTool");
		var state = tool.text() == "展开";
		if(state){
			tool.text("收起");
			obj.find(".queryFields form").show();
		}else{
			tool.text("展开");
			obj.find(".queryFields form").hide();
		}
		
		onion.faces.modalPanel.autoHeight(panelId);
	}
};

/**
 * 消息提示ModalPanel
 */
onion.faces.message = {
	show: function(content) {
		$("#messagePopup .messageContent").html(content);
		RichFaces.$("messagePopup").show();
	},

	hide: function() {
		RichFaces.$("messagePopup").hide();
	}
};

onion.faces.processingMP = {
		id : "processingMP",

		init: function() {
			this.comp = $("#" + this.id)[0].component;
		},

		show: function(content,params) {
			Richfaces.showModalPanel(this.id);
		},

		hide: function() {
			this.comp.hide();
		}
};

onion.faces.extraInfo = {

	show : function (){
		$(this).siblings(".extraInfo").show();
	},

	hide : function() {
		$(this).siblings(".extraInfo").hide();
	}
};

onion.faces.showQueryParamError = function(formId,errors){
	var first = true;
	var types = document.getElementById(formId).types;
	for(var key in errors){
		var name = types[key];
		var element = $("[name='" + name + "']").addClass("error");
		if(first)
			element.focus();

		first = false;
	}
};

onion.faces.cleanQueryErrors = function(form){
	$(".error",form).removeClass("error");
};

onion.register("onion.faces.suggestionInput");
onion.faces.suggestionInput.setIgnoreInput = function(id,value){
	$("[name='com.ai.core.jsf.suggestion.ignoreInput-" + id + "']").val(value);
};

/**
 * 导出按钮点击的时候执行这个方法
 */
onion.faces.onexport=function(element){};

//============== INPUT BEHAVIOR ===============
onion.faces.inputItem = {};
onion.faces.inputItem.tip = {	
	show : function(e) {
		if (null == $(e).data("qtip")) {			
			onion.faces.inputItem.tip.init(e);
			$(e).trigger("mouseover");
		}
	},
	init : function(e) {	
		$(e).qtip( {									
			style : this.defaultStyle
		});
	}
	 
};

onion.faces.inputItem.tip.defaultStyle = {

	border : {
		width : 1,
		radius : 3,
		color : '#F9E98E'
	},
	title : {
		background : '#F0DE7D',
		color : '#A27D35'
	},
	background : '#FFFBE8',
	color : '#A27D35',
	tip : true
};


onion.faces.extendProperty = {
	add : function(id) {
		$('#' + id + 'AddPanel').show();
		// 这个地方很奇怪，在IE8下,必须连续调用两次才有效果
		$('.' + id + 'exp_key').focus();
	},
	onAdd : function(method, id) {
		var key = $('.' + id + 'exp_key').val();
		var value = $('.' + id + 'exp_value').val();
		var returnValue = method(key, value);
		if (typeof returnValue !== 'boolean') {
			returnValue = true;
		}
		return returnValue;
	},
    validation : function(key, value) {
        var legal = true;
        var reg = new RegExp("^[\\d\\s]+$");
        if (!key || '' == key || !value || '' == value) {
            legal = false;
        }
        if (legal && reg.test(key)) {
            legal = false;
        }
        if (!legal) {
            alert('属性名和属性值不能为空，且属性名不能为纯数字');
        }
        return legal;
    }
};


onion.faces.toggleLimitText = function(obj,type){
	obj = $(obj);
	if(type == 'click'){
		var state = obj.attr("state");
		state = typeof state == 'undefined' ? 'limited' : state;
		if(state == 'limited'){
			obj.find(".limited").hide();
			obj.find(".expanded").show();
			obj.attr("state","expanded");
		}else{
			obj.find(".expanded").hide();
			obj.find(".limited").show();
			obj.attr("state","limited");
		}
	}else{
		if(obj.attr("tipInited") == null){
			obj.qtip({
			   content: obj.find(".expanded").text(),
			   show:{delay:0,when:{event:"mouseover"},ready:true},
			   position:{adjust:{resize:true,screen:true}} 
			});
			obj.attr("tipInited",true);
		}
	}
};

/**
 * 初始化浮动的表单按钮，注意如果要使用，需要拷贝full.css中的部分内容到项目共公共css中
 * 然后在formPanel.onrefresh中根据配置调用本方法
 */
onion.faces.showFormButtons = function(type){	
	//Go to hell, IE6
	if($.browser.msie && $.browser.version == 6){
		$("#formPanelContainer .editorForm .formBox_buttons").show();
		return;
	}
	
	if(typeof type == 'undefined'){
		if(document.cookie.indexOf('formButtons.layout=fixed') > -1)
			type = "fixed";
		else if(document.cookie.indexOf('formButtons.layout=auto') > -1)
			type = "auto";
		else
			type = "";
	}
	
	if(type == "fixed"){
		var editorForm = $("#formPanelContainer form.editorForm");
		editorForm.addClass("editorForm_fixed");
		editorForm.find(".formBox_buttons").show();
	}else if(type == "auto"){
		var seeHeight = $("#formPanelContentDiv").height();
		var scrollHeight = $("#formPanelContentDiv").attr("scrollHeight");
		if(seeHeight < scrollHeight){
			var editorForm = $("#formPanelContainer form.editorForm");
			editorForm.addClass("editorForm_fixed");
			editorForm.find(".formBox_buttons").show();
		}else
			$("#formPanelContainer .editorForm .formBox_buttons").show();
	}else{
		$("#formPanelContainer .editorForm .formBox_buttons").show();
	}
};



(function($) {
    $.fn.attrs = function() {
        var attributes = {}; 

        if(!this.length)
            return this;

        $.each(this[0].attributes, function(index, attr) {
            attributes[attr.name] = attr.value;
        }); 

        return attributes;
    };
})(jQuery);

//JMS的JS
onion.register("onion.faces.jms");
onion.faces.jms.open = function(url){
	window.open(url);
};

onion.faces.jms.hide = function(isWindow){
	if(!isWindow){
		onion.faces.formPanel.hide();
	}else{
		window.close();
	}
};

/**
 * formBox的展开和收起小工具
 */
onion.faces.toggleFormBox = function(tool){
	var box = $(tool).closest(".formBox");
	tool = $(tool);
	if(box.hasClass('formBox_closed')){
		tool.removeClass("form_box_tool_down")
			.addClass("form_box_tool_up")
			.attr("title","点击收起此表单区块");
		box.removeClass('formBox_closed');
	}else{
		tool.removeClass("form_box_tool_up")
			.addClass("form_box_tool_down")
			.attr("title","点击展开此表单区块");
		box.addClass('formBox_closed');
	}
};

if(window.parent != null && window.parent.frames["main"] != null){
	$(window.parent.frames["main"]).bind('resize', function() {
	    if(this.parent != null){
	    	var width,height;
	    	if(window.ActiveXObject){
	    		width = $(window.parent.frames['main']).width();
	    		height = $(window.parent.frames['main']).height();		
	    	}else{
	    		width = $(window.parent.frames['main']).width() - 5;
	    		height = $(window.parent.frames['main']).height() - 5;
	    	}

	    	$("#globalMPContentDiv").css("height",height + "px").css("width",width + "px");
	    }
	});
}